package lib

import (
	"fmt"
	"fruit/tools/proto/proto_out/base"
	"fruit/tools/redis"

	// "github.com/go-redis/redis/v8/internal/proto"
	"google.golang.org/protobuf/proto"
)

type lib_redis_mgr struct {
	redis_sub *redis.Redis
	redis_pub *redis.Redis
}

var lib_rds lib_redis_mgr

func func_redis_start() {
	if lib_rds.redis_pub == nil {
		//	todo redis 需修改为 chan 防止单次操作 阻塞所有协程 可仿iactor push和pop
		lib_rds.redis_pub = redis.Connect("localhost:6379", "", 0)
	}
	if lib_rds.redis_sub == nil {
		lib_rds.redis_sub = redis.Connect("localhost:6379", "", 0)
	}
}

func redis_sub() {
	if lib_rds.redis_sub != nil {
		redis.Subscribe(lib_rds.redis_sub, pid+".*", true, &lib_rds)
	}
}

func (my *lib_redis_mgr) close() {
	if my.redis_sub != nil {
		redis.Close(my.redis_sub)
		my.redis_sub = nil
	}
}

func (my *lib_redis_mgr) Incr(idx_type string) int64 {
	// fmt.Println("tyee", my, my.redis_pub)
	if my.redis_pub != nil {
		idx, err := redis.Incr(my.redis_pub, idx_type, 1)
		if err == nil {
			return idx
		}
	}
	return 0
}

func (my *lib_redis_mgr) publish(channel string, data []byte) int64 {
	// fmt.Println("tyee", my, my.redis_pub)
	if my.redis_pub != nil {
		idx, err := redis.Publish(my.redis_pub, channel, data)
		if err == nil {
			return idx
		}
	}
	return 0
}

func (my *lib_redis_mgr) srandmember(key string) string {
	if my.redis_pub != nil {
		resp := redis.Do(my.redis_pub, "SRANDMEMBER", key)
		if resp != nil && resp.Err() == nil {
			// fmt.Println("123", resp)
			val, _ := resp.Result()
			return val.(string)
		}
	}
	return ""
}

func (my *lib_redis_mgr) sadd(key string, val string) int {
	if my.redis_pub != nil {
		resp := redis.Do(my.redis_pub, "SADD", key, val)
		if resp != nil && resp.Err() == nil {
			val, _ := resp.Int()
			return val
		}
	}
	return 0
}

func (my *lib_redis_mgr) del(key string) {
	if my.redis_pub != nil {
		resp := redis.Do(my.redis_pub, "del", key)
		if resp != nil && resp.Err() == nil {
		}
	}
}

func (my *lib_redis_mgr) SubSuccess(Channel string, Count int, Kind string) {
	fmt.Println("Subscription", Channel, Count, Kind)
}
func (my *lib_redis_mgr) SubRecv(Channel string, Pattern string, Payload string) {
	if len(Payload) > 0 {
		base_msg := &base.Remote{}
		err := proto.Unmarshal([]byte(Payload), base_msg)
		if err != nil {
			fmt.Println("SubRecv proto Unmarshal error", err)
			return
		}
		fmt.Println("Subscription Message", base_msg.From, Channel, base_msg.FuncName, base_msg.EventId)
		deal(base_msg.From, Channel, base_msg.FuncName, base_msg.EventId, true, base_msg.Data)
	}
}

func Publish(channel string, data []byte) int64 {
	// fmt.Println("tyee", my, my.redis_pub)
	if lib_rds.redis_pub != nil {
		idx, err := redis.Publish(lib_rds.redis_pub, channel, data)
		if err == nil {
			return idx
		}
	}
	return 0
}
